package zz.extjs.servlet;

import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import zz.extjs.util.FindFile;

import com.teetaa.util.ImageHepler;

public class ZoomImage extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();

		// 登录检查
		Object zz = request.getSession().getAttribute("user1");

		if (zz == null) { // 先检查用户是否处于登入状态
			response.sendRedirect("logout.jsp");
			return;
		}

		int imageWidth = Integer.parseInt(request.getParameter("txt_width"));
		int imageHeight = Integer.parseInt(request.getParameter("txt_height"));
		int cutTop = Integer.parseInt(request.getParameter("txt_top"));
		int cutLeft = Integer.parseInt(request.getParameter("txt_left"));
		int dropWidth = Integer.parseInt(request.getParameter("txt_DropWidth"));
		int dropHeight = Integer.parseInt(request
				.getParameter("txt_DropHeight"));
		// float imageZoom = Float.parseFloat(request.getParameter("txt_Zoom"));
		String picname = request.getParameter("picname");
		String pbid = request.getParameter("pbid");
		if(pbid != null && "".equals(pbid.trim()) && picname != null && "".equals(picname.trim()) ){
			out.print("文件名错误！");
			return;
		}

		Rectangle rec = new Rectangle(cutLeft, cutTop, dropWidth, dropHeight);
		String filepath = FindFile.getParentPath(this.getServletContext()
				.getRealPath("")) + "/pbimg/";
		//String ext = picname.substring(picname.lastIndexOf(".") + 1);
		File desfile = FindFile
				.getNewFileName(filepath, pbid.trim(), "jpg") ;
		if(desfile == null  ){
			out.print("此护照号图片过多，请先清理再上传！");
			return;
		}

		File uploadfile = new File(this.getServletContext().getRealPath("")
				+ "/UploadPhoto/" + picname);
		saveSubImage(uploadfile, desfile, imageWidth, imageHeight,
				rec);
		ImageHepler.delAllFile(uploadfile.getParentFile());	//删除历史目录中文件
		
		response.sendRedirect("pbimg.jsp?pbid=" + pbid+"&"+(new Date().getTime()) );
	}

	private static void saveSubImage(File srcImageFile, File descDir,
			int width, int height, Rectangle rect) throws IOException {
		ImageHepler.cut(srcImageFile, descDir, width, height, rect);
	}
}